package com.dlc.yunguang.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import butterknife.BindView;
import butterknife.OnClick;
import butterknife.Unbinder;
import com.dlc.commonlibrary.ble.UHFR2000Helper;
import com.dlc.commonlibrary.dialog.DoResultDialog;
import com.dlc.commonlibrary.dialog.ReadNumsDialog;
import com.dlc.commonlibrary.dialog.SureDialog;
import com.dlc.commonlibrary.dialog.YesNoDialog;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.ToastUtil;
import com.dlc.yunguang.activity.OrderManageActivity;
import com.dlc.yunguang.activity.TagManageActivity;
import com.dlc.yunguang.base.BaseFragment;
import com.dlc.yunguang.helper.DBManager;
import com.dlc.yunguang.helper.UserHelper;
import com.dlc.yunguang.net.bean.HotelRfidBean;
import com.dlc.yunguang.R;
import com.dlc.yunguang.activity.CountingProductActivity;
import com.dlc.yunguang.activity.QueryRfidActivity;
import com.dlc.yunguang.activity.ReWashActivity;
import com.dlc.yunguang.activitynew.LaundryOutboundActivity;
import com.dlc.yunguang.activitynew.RecycleActivity;
import com.dlc.yunguang.activitynew.ReturnActivity;
import com.dlc.yunguang.activitynew.SelectDistributeActivity;
import com.dlc.yunguang.activitynew.SelectOrderActivity;
import com.seuic.uhf.EPC;

import java.util.ArrayList;
import java.util.List;

/**
 * 仓管员首页
 */
public class HomeStorekeeperFragment extends BaseFragment {

    @BindView(R.id.item_1) TextView mItem1;
    @BindView(R.id.item_2) TextView mItem2;
    @BindView(R.id.item_3) TextView mItem3;
    @BindView(R.id.item_4) TextView mItem4;
    @BindView(R.id.item_5) TextView mItem5;
    Unbinder unbinder;
    private DoResultDialog doResultDialog;
    private ReadNumsDialog doReadDialog;
    private StringBuilder mStringBuilder;
    public static final String EXTRA_RFIDS = "rfids";
    public static final int chuku_equestCode = 200;
    private Handler mHandler = new Handler();
    private DBManager dbManager;
    private  Class<? extends Activity> mClass;

    private boolean readState = false;
    @Override
    protected int getLayoutId() {
        return R.layout.fragment_home_storekeeper;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
        @Nullable Bundle savedInstanceState) {
        doReadRFID();
        doResult();
        dbManager = DBManager.getInstance(getActivity());
        return super.onCreateView(inflater, container, savedInstanceState);
    }



    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (unbinder != null) {
            unbinder.unbind();
        }
    }

    @OnClick({ R.id.item_1, R.id.item_2, R.id.item_3, R.id.item_4, R.id.item_5 ,
            R.id.item_6, R.id.item_7, R.id.item_8, R.id.item_reWash,R.id.item_return})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.item_1:
                if (check("1")) {
                    startActivity(new Intent(getActivity(), OrderManageActivity.class));//OrderManageActivity
               }
                break;
            case R.id.item_2:
                //ToastUtil.showOne(getActivity(), R.string.home_storekeeper_block_2);
                if (check("2")) {
                    startActivity(new Intent(getActivity(), TagManageActivity.class));
                }
                break;
            case R.id.item_3:
                //ToastUtil.showOne(getActivity(), R.string.home_storekeeper_block_3);
                if (check("3")) {
                    startActivity(new Intent(getActivity(), CountingProductActivity.class));
                }
                break;
            case R.id.item_4:
                //ToastUtil.showOne(getActivity(), R.string.home_storekeeper_block_6);
                if (check("4")) {
                    startActivity(new Intent(getActivity(), QueryRfidActivity.class));
                }
                break;
            case R.id.item_5:

                if (check("7")) {
                    startActivity(new Intent(getActivity(), SelectOrderActivity.class));
                }
                break;
            case R.id.item_6:

                if (check("5")) {
                    startActivity(new Intent(getActivity(), LaundryOutboundActivity.class));
                }
                //test();
                break;
            case R.id.item_7:
                if (check("6")) {
                    rfidsList.clear();
                    mClass = RecycleActivity.class;//科室回收
                    getData();
                    //test();
                }
                break;
            case R.id.item_8:

                if (check("8")) {
                    startActivity(new Intent(getActivity(), SelectDistributeActivity.class));//科室分发
                }
                break;

            case R.id.item_reWash:
                if (check("9")) {
                    rfidsList.clear();
                    mClass = ReWashActivity.class;
                    getData();
                    //test();
                }
                break;
            case R.id.item_return:
                if (check("10")) {
                    rfidsList.clear();
                    mClass = ReturnActivity.class;
                    getData();
                    //test();
                }
                break;
        }
    }

    private boolean check(String aa){
        if (UserHelper.get().getPermission().contains(aa)){
            return true;
        }
        ToastUtil.show(getActivity(),"没有权限");
        return false;
    }

    /**
     * 检查自动清空前一天数据
     */
    private void setDbManager(){
        List<HotelRfidBean> list = dbManager.queryLabelListHotel();
        if (list.size() > 0) {
            showWaitingDialog("正在清理前一天",false);
            dbManager.deleteLabel();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    dismissWaitingDialog();
                    isDeleteDb();
                }
            }, 2000);
        }else {
            isDeleteDb();
        }

    }

    /**
     * 是否清空保存的数据
     */
    private void isDeleteDb(){
        List<HotelRfidBean> list = dbManager.queryLabelListHotel();

        if (list.size() > 0){
            SureDialog sureDialog = new SureDialog(getContext(), "是否清空未提交的数据");
            sureDialog.setOnCallBackListener(new SureDialog.OnCallBack() {
                @Override
                public void sure() {
                    YesNoDialog yesNoDialog = new YesNoDialog(getContext(), "是否清空未提交的数据");
                    yesNoDialog.setOnCallBackListener(new YesNoDialog.OnCallBack() {
                        @Override
                        public void sure() {
                            dbManager.deleteLabelAllHotel();
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    getData();
                                    ToastUtil.show(getContext(),"已清空");
                                }
                            },1000);
                        }

                        @Override
                        public void cancle() {
                            getData();

                        }
                    });

                }

                @Override
                public void cancle() {
                    //test();
                   getData();
                }
            });
        }else {
            //test();
            getData();
        }
    }
    private void test(){
        ArrayList<String> mList = new ArrayList<>();
        mList.add("01350740C8E2");
      //  mList.add("00393B7B3411");
        Intent intent = new Intent(getActivity(), mClass);
        intent.putExtra(EXTRA_RFIDS, mList);
        startActivityForResult(intent, chuku_equestCode);
    }

    private ArrayList<String> rfidsList = new ArrayList<>();
    private void getData(){
        readState = true;
        doReadDialog.showWorking(true);
        UHFR2000Helper.getInstance().readData(new UHFR2000Helper.BleCallBack() {
            @Override
            public void readDatas(List<EPC> data) {
                LogPlus.e("mEPCList="+data.toString());
                if (data.size() > 0){
                    doReadDialog.dismiss();
                    doResultDialog.showResultAndDismiss(true, 1000);
                    ArrayList<String> mList = new ArrayList<>();
                    String str = "";
                    for (EPC epc : data) {
                        str = epc.getId();
                        if (str.length() > 14) {
                            str = str.substring(str.length() - 12, str.length());
                            mList.add(str);
                        }
                    }

                    Intent intent = new Intent(getActivity(), mClass);
                    intent.putExtra(EXTRA_RFIDS, mList);
                    startActivityForResult(intent, chuku_equestCode);
                }else {
                    doReadDialog.dismiss();
                    doResultDialog.setFailedText("读取不到RFID");
                    doResultDialog.setFailedImage(R.mipmap.ic_error);
                    doResultDialog.showResultAndDismiss(false, 2000);

                }
            }

            @Override
            public void readNums(final int nums) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (readState) {
                            doReadDialog.showWorking(nums);
                        }
                    }
                });

            }
        });
    }


    private void doReadRFID() {
        doReadDialog =
                ReadNumsDialog.newDialog(getActivity())
                .setSuccessImage(R.mipmap.ic_success)
                .setSuccessText(getString(R.string.scan_over))
                .setButton("完成扫描", new ReadNumsDialog.OnClickButtonListener() {
                    @Override
                    public void onClickButton(ReadNumsDialog dialog) {
                        readState = false;
                        UHFR2000Helper.getInstance().stopRead();

                    }
                });

        doReadDialog.setCancelable(false);

    }
    private void doResult() {

        doResultDialog = DoResultDialog.newDialog(getActivity())
            .setWorkingText(getString(R.string.commit_counting_result))
            .setSuccessImage(R.mipmap.ic_success)
            .setSuccessText(getString(R.string.commit_counting_result_success));

        doResultDialog.setCancelable(false);
    }
}


